import { HOST, OdataHOST } from './constant';
/**
 * 将对象转成 a=1&b=2的形式
 * @param obj 对象
 */
function obj2String(obj, arr = [], idx = 0) {
  for (let item in obj) {
    arr[idx++] = [item, obj[item]];
  }
  return new URLSearchParams(arr).toString();
}

/**
 * 真正的请求
 * @param url 请求地址
 * @param options 请求参数
 * @param method 请求方式
 */
const commonFetch = async (url, options, method = 'GET') => {
  const searchStr = obj2String(options);
  let initObj = {};
  if (method === 'GET') {
    // 如果是GET请求，拼接url
    url += '?' + searchStr;
    initObj = {
      method: method
      // headers: new Headers({
      //   'Accept': 'application/json',
      //   'content-type': 'application/json',
      // }),
    };
  } else {
    initObj = {
      method: method,
      headers: new Headers({
        Accept: 'application/json',
        'content-type': 'application/json'
      }),
      body: searchStr
    };
  }
  return fetch(
    'https://ecc.weadmin.com/rest/security/userinfos?token=A086E4F67FA846BF9B574B3F71DF1C05',
    initObj
  );
};

export const request = async (url, options, method) => {
  return commonFetch(HOST + url, options, method);
};
export const requestOdata = async (url, options, method) => {
  return commonFetch(OdataHOST + url, options, method);
};
